package com.xms.event.service;

import com.xms.event.core.IEventPublisher;
import com.xms.logging.service.IAppLogging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * <p>
 * 事件发布者
 * </p>
 *
 * @author migo
 * @since 2021/9/26
 */
@Service
public class EventPublisher implements IEventPublisher {
    private static Logger logger = LoggerFactory.getLogger(EventPublisher.class);
    private IAppLogging _appLogging;
    private ApplicationEventPublisher _applicationEventPublisher;

    @Autowired
    public EventPublisher(IAppLogging appLogging,
                          ApplicationEventPublisher applicationEventPublisher) {
        _appLogging = appLogging;
        _applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 发布事件
     *
     * @param e        事件对象
     * @param <TEvent> 事件类型
     */
    @Override
    public <TEvent> void publish(TEvent e) {
        //开启异步线程时加入当前请求，或者在事件参数中携带当前用户
        RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
        _applicationEventPublisher.publishEvent(e);
    }
}
